package com.xktpx.service.impl;

import com.xktpx.dao.WxPostDataInfoDao;
import com.xktpx.entity.WxPostDataInfoEntity;
import com.xktpx.service.WxPostDataInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service("wxPostDataInfoService")
public class WxPostDataInfoServiceImpl extends ServiceImpl<WxPostDataInfoDao, WxPostDataInfoEntity> implements WxPostDataInfoService {

    @Autowired
    protected WxPostDataInfoDao wxPostDataInfoDao;

    @Override
    @Transactional
    public String nofify(Map<String, String> map) {
        if (map.get("return_code").equals("SUCCESS")) {
            String outTradeNo = map.get("out_trade_no");
            if (!StringUtils.isEmpty(outTradeNo)) {
                // 判断对应out_trade_no的数据是否存在，存在直接返回
                WxPostDataInfoEntity wxPostDataInfoEntity = wxPostDataInfoDao.selectByOutTradeNo(outTradeNo);
                if(wxPostDataInfoEntity != null){
                    return "fail";
                }else{
                    WxPostDataInfoEntity newWxPostDataInfoEntity = new WxPostDataInfoEntity();
                    newWxPostDataInfoEntity.setAppid(map.get("appid"));
                    newWxPostDataInfoEntity.setBanktype(map.get("bank_type"));
                    newWxPostDataInfoEntity.setCashfee(map.get("cash_fee"));
                    newWxPostDataInfoEntity.setIssubscribe(map.get("is_subscribe"));
                    newWxPostDataInfoEntity.setNoncestr(map.get("nonce_str"));
                    newWxPostDataInfoEntity.setOpenid(map.get("openid"));
                    newWxPostDataInfoEntity.setOuttradeno(map.get("out_trade_no"));
                    newWxPostDataInfoEntity.setResultcode(map.get("result_code"));
                    newWxPostDataInfoEntity.setReturncode(map.get("return_code"));
                    newWxPostDataInfoEntity.setTimeend(map.get("time_end"));
                    newWxPostDataInfoEntity.setTotalfee(map.get("total_fee"));
                    newWxPostDataInfoEntity.setTradetype(map.get("trade_type"));
                    newWxPostDataInfoEntity.setTransactionid(map.get("transaction_id"));
                    wxPostDataInfoDao.insert(newWxPostDataInfoEntity);

                    String[] dataArray = outTradeNo.split("_");
                    if(dataArray.length > 1){
                        String orderId = outTradeNo.split("_")[1];
                        // TODO 微信支付成功，处理自己的业务逻辑，更改订单状态上传订单号之类的
                    }
                }
                return "success";
            }
        }
        return "fail";
    }
}
